const fs = require('fs');
const path = require('path');
const glob = require('glob');
const command = require('commander');

const root_path = "D:\\git\\DocWebService\\example\\content";

class DocTools {

  constructor() {
  }

  /**
   * 获取文件后缀
   * @param {string} url
   */
  getSuffix(url) {
    var arr = url.split('.');
    var len = arr.length;
    return arr[len - 1];
  }

  /**
   *
   * @param {string} filePath
   * @param {number} type
   */
  readDirFileName(filePath, type) {
    console.log("当前目录：", filePath);
    var fileNameArray = [];
    fs.readdirSync(filePath, 'utf-8').forEach((fileName) => {
      var stat = fs.statSync(path.join(filePath, fileName));
      if (stat.isFile()) {
        if (this.getSuffix(fileName) == type) {
          //console.log("文件：", path.join(filePath,fileName));
          fileNameArray.push({name: fileName, path: path.normalize(filePath)});
        }
      } else if (stat.isDirectory() && fileName !== ".git") {
        // console.log("文夹：", fileName);
        fileNameArray = fileNameArray.concat(this.readDirFileName(path.join(filePath, fileName), type));
      }
    });
    return fileNameArray;
  }

  /**
   * 修改文件名称
   * @param {*} sPath
   * @param {*} fileName
   * @param {*} newName
   */
  reFimeName(sPath, oldName, newName) {
    if (!newName) {
      newName = this.newFileName(oldName);
    }
    oldName = path.join(sPath, oldName);
    newName = path.join(sPath, newName);

    if (oldName == newName) {
      return;
    }

    fs.rename(oldName, newName, (err) => {
      if (err) {
        console.log("修改文件名失败：", err, oldName, newName);
        return;
      }
      console.log("修改文件名成功：", oldName, newName);
    });
  }

  /**
   * 批量的重新命名文件名称 根据文件名称是否有 [xxx] 的符号
   */
  changeAllFileName(rootPath) {
    let files = this.readDirFileName(rootPath, 'md');
    files.forEach((ele) => {
      //console.log("修改的文件：", JSON.stringify(ele));
      this.reFimeName(ele.path, ele.name);
    });
  }

  /**
   * 获取 获取新的文件名称
   * @param {string} oldName
   */
  newFileName(oldName) {
    var strArray = oldName.split(".");
    var sub = oldName.match(/\[(\S*)\]/);
    if (sub) {
      return strArray.length > 1 ? sub[1] + "." + strArray[strArray.length - 1] : sub;
    }
    return oldName;
  }

  /**
   * 保存数据到 summary.json 文件中
   * @param {*} data
   */
  saveFileName(data) {
    let tmp = data.join('\n');
    if (typeof data == "object") {
      tmp = JSON.stringify(data);
    } else {
      tmp = data;
    }
    console.log("要写入的文件数据：", JSON.stringify(tmp));
    fs.writeFile(path.join(__dirname, "summary.json"), tmp, function (err) {
      if (err) throw err;
      console.log("summary.json 生成成功");
    });
  }

  /**
   * 获取指定路径下的所有文件 和目录列表
   * @param {*} filePaths
   */
  getShortPath(root) {
    let filePaths = glob.sync(root + "/**/*");

    let shortPaths = [];
    filePaths.forEach(filePath => {
      if (fs.lstatSync(filePath).isDirectory()) {
        let shortPath = path.normalize(filePath).replace(path.normalize(root), '').trim();
        let slug = shortPath.split('\\').join('/');

        let arr = slug.split("/");
        let filename = this.newFileName(arr[arr.length - 1]);
        filename = filename.split('.')[0];
        shortPaths.push({file: slug, alias: filename});
      }else{
        console.log("[INFO] ignore case it is file :"+filePath);
      }

    });
    console.log(shortPaths);
    return shortPaths;
  }

  readFileData(file) {
    let data = fs.readFileSync(path.join(__dirname, file), 'utf8');
    return data;
  }

  _StringChange(a, b) {
    let bufa = new Buffer(a);
    let bufb = new Buffer(b);
    for (let i = 0; i < bufa.length; i++) {
      bufb[i] = bufa[i]
    }
    return bufb.toString('utf8');
  }


  /**
   * ^[\/\*\n\bTitle][^]*[\n\bsort:\s+][0-9]\d*\n\*\/
   * @param {*} fileName
   * @param {*} datas
   */
  _writHeadInfo(fileName, datas) {
    //console.log("fileName:", fileName, " datas:", datas);
    fs.readFile(fileName, 'utf8', (err, files) => {
      if (err) {
        throw err;
      }
      let toChange = "/*\r\nTitle: " + datas.Title + "\r\nSort: " + datas.sort + "\r\n*/";
      let headDatas = files.substring(0, 200);
      if (/^[\/\*\r\n\bTitle:][^]*[\r\n\bSort:\s+][0-9]\d*\r\n\*\//g.test(headDatas)) {
        //console.log("替换前数据：headDatas:", headDatas);
        let result = headDatas.replace(/^[\/\*\r\n\bTitle:][^]*[\r\n\bSort:\s+][0-9]\d*\r\n\*\//g, toChange);
        //console.log("替换成功后数据：", result);
        files = this._StringChange(result, files);
        //console.log("文件：",files);

      } else {
        files = toChange + "\r\n" + files;
      }

      fs.writeFile(fileName, files, 'utf8', function (err) {
        if (err) {
          console.log("写入失败", toChange);
          return;
        }
        //console.log("替换成功");
      });
    });

  }

  /**
   * 根据 summary.json 写入排序头信息到文件中
   * @param {string} rootPath 指定排序的目录
   */
  WritfileSort(rootPath) {
    //读取所有文件 md
    let fileNames = this.readDirFileName(path.normalize(rootPath), 'md');
    let sortData = JSON.parse(this.readFileData("summary.json"));
    fileNames.forEach(file => {
      let sort = 0;
      sortData.forEach(sd => {
        sort++;
        if (sd.file.indexOf(file.name) > -1) {
          this._writHeadInfo(path.join(file.path, file.name), {Title: sd.alias, sort: sort});
          return;
        }
      });
    });

  }
}


function run() {
  command.version('0.1.0', '-v, --version')
    .option('-s, --summary <path>', 'add a summary.join')
    .option('-r, --rename <path>', 'batch change file use the [xxx] name')
    .option('-a, --auto_sort <path>', 'insertion automatic sequence information for summary.json')
    .parse(process.argv);
  let a = new DocTools();

  if (command.summary) {
    console.log("--summary:", command.summary);
    //保存目录结构
    a.saveFileName(a.getShortPath(command.summary));
  } else if (command.rename) {
    console.log("--rename:", command.rename);
    a.changeAllFileName(command.rename);
  } else if (command.auto_sort) {
    console.log("--auto_sort:", command.auto_sort);
    // 根据文件 summary.json 排序
    a.WritfileSort(command.auto_sort);
  }

  a.saveFileName(a.getShortPath(root_path));
}

run();

module.exports = DocTools;
